<template>
	<el-container>
		<div class="left-panel">
			<div class="right-panel-search" style="width: 100%; margin-top: 5px; margin-bottom: 5px">
				<div class="panel-search-box">
					<span class="demonstration" style="margin-left: 10px">账号:</span>
					<el-input @keyup.enter="upsearch" v-model="search.staffName" placeholder="输入账号"
						style="margin-left: 10px; width: 180px" clearable></el-input>
				</div>
				<div class="panel-search-box">
					<span class="demonstration" style="margin-left: 10px">姓名:</span>
					<el-input @keyup.enter="upsearch" v-model="search.realName" placeholder="输入姓名"
						style="margin-left: 10px; width: 180px" clearable></el-input>
				</div>
				<div class="panel-search-box">
					<span class="demonstration" style="margin-left: 10px">组织:</span>
					<el-input @keyup.enter="upsearch" v-model="search.orgName" placeholder="输入组织"
						style="margin-left: 10px; width: 180px" clearable></el-input>
				</div>
				<div class="panel-search-box">
					<span class="demonstration" style="margin-left: 10px">角色:</span>
					<el-input @keyup.enter="upsearch" v-model="search.role" placeholder="输入角色"
						style="margin-left: 10px; width: 180px" clearable></el-input>
				</div>
				<div class="panel-search-box">
					<span class="demonstration" style="margin-left: 10px">功能权限:</span>
					<el-input @keyup.enter="upsearch" v-model="search.actionPower" placeholder="输入最终功能权限"
						style="margin-left: 10px; width: 180px" clearable></el-input>
				</div>

				<div class="panel-search-box">
					<span class="demonstration" style="margin-left: 10px">数据权限:</span>
					<el-input @keyup.enter="upsearch" v-model="search.dataPower" placeholder="输入最终数据权限"
						style="margin-left: 10px; width: 180px" clearable></el-input>
				</div>
				<div class="panel-search-box">
					<el-button type="primary" style="margin-left: 10px" @click="upsearch">查询</el-button>
					<el-button type="" @click="cleanSearch">清空</el-button>
					<el-popconfirm title="确定要导出所有数据吗？" @confirm="downloadFile">
						<template #reference>
							<el-button type="primary" :loading="exportLoading">导出</el-button>
						</template>
					</el-popconfirm>
				</div>
			</div>
		</div>
		<el-header style="display: none"></el-header>
		<el-main class="nopadding">
			<scTable ref="table" border stripe :apiObj="apiObj" row-key="id" @selection-change="selectionChange">
				<!-- <el-table-column align="center" type="selection" width="50"></el-table-column> -->
				<el-table-column align="center" label="账号" prop="staffName"></el-table-column>
				<el-table-column align="center" label="姓名" prop="realName"></el-table-column>
				<el-table-column align="center" label="组织" prop="orgName"></el-table-column>
				<el-table-column align="center" label="角色" prop="role"></el-table-column>
				<el-table-column align="center" label="最终功能权限" prop="actionPower" width="200"
					class-name="long-text"></el-table-column>
				<el-table-column align="center" label="最终数据权限" prop="dataPower" width="200"
					class-name="long-text"></el-table-column>
				<el-table-column label="操作" align="center" width="300">
					<template #default="scope">
						<el-button-group>
							<el-button text type="primary" size="small"
								@click="showFunctionPower(scope.row, scope.$index)">查看功能权限
							</el-button>
							<el-button text type="primary" size="small"
								@click="showDataPower(scope.row, scope.$index)">查看数据权限
							</el-button>
						</el-button-group>
					</template>
				</el-table-column>

			</scTable>
		</el-main>
	</el-container>
	<show-dialog v-if="dialog.show" ref="showPower" @success="handleSaveSuccess" @closed="dialog.show = false">
	</show-dialog>
</template>

<script>
import axios from 'axios'
import config from '@/config'
import showDialog from './showPower'

export default {
	name: 'powerSearch',
	components: { showDialog },
	data() {
		return {
			index: false,
			dialog: {
				show: false
			},
			apiObj: this.$API.powerSearch.list,

			selection: [],
			search: {
				// keyword: null
			},
			exportLoading: false
		}
	},
	methods: {
		//添加
		// add() {
		// 	this.dialog.save = true
		// 	this.$nextTick(() => {
		// 		this.$refs.saveDialog.open()
		// 	})
		// },
		//编辑
		// table_edit(row) {
		// 	this.dialog.edit = true
		// 	this.$nextTick(() => {
		// 		this.$refs.editDialog.open('edit').setData(row)
		// 	})
		// },
		//查看
		// table_show(row) {
		// 	this.dialog.edit = true
		// 	this.$nextTick(() => {
		// 		this.$refs.editDialog.open('show').setData(row)
		// 	})
		// },
		//删除
		// async table_del(row) {
		// 	var reqData = { id: row.id, orgId: row.orgId }
		// 	var res = await this.$API.dept.delete.post({ data: reqData });
		// 	if (res.code == 0) {
		// 		this.$refs.table.refresh()
		// 		this.$message.success("删除成功")
		// 	} else {
		// 		this.$alert(res.message, "提示", { type: 'error' })
		// 	}
		// },
		//表格选择后回调事件
		selectionChange(selection) {
			this.selection = selection;
		},
		//搜索
		upsearch() {
			this.$refs.table.upData(this.search)
		},
		cleanSearch() {
			this.search = {}
			this.$refs.table.reload()

		},
		//本地更新数据
		handleSaveSuccess(data, mode) {
			this.dialog.show = false
		},
		//导出
		async downloadFile() {
			this.exportLoading = true
			try {
				// 发起请求获取文件流
				const apiUrl = `${config.API_URL}/permissions/exportExcel`
				const response = await axios.get(apiUrl, {
					responseType: 'blob',
					params: this.search
				})

				// 获取文件类型和文件名
				const contentType = response.headers['content-type']
				const contentDisposition = response.headers['content-disposition']
				let fileName = ''
				if (contentDisposition && contentDisposition.indexOf('attachment') !== -1) {
					// 尝试从 filename* 参数中提取文件名
					const filenameStarRegex = /filename\*=([^;\n]*)/
					const matches = filenameStarRegex.exec(contentDisposition)
					if (matches != null && matches[1]) {
						// 解码文件名
						const [encoding, encodedFileName] = matches[1].split("''")
						if (encoding.toLowerCase() === 'utf-8') {
							fileName = decodeURIComponent(encodedFileName)
						}
					} else {
						// 如果 filename* 参数不存在，尝试从 filename 参数中提取文件名
						const filenameRegex = /filename=([^;\n]*)/
						const matches = filenameRegex.exec(contentDisposition)
						if (matches != null && matches[1]) {
							fileName = decodeURIComponent(matches[1].replace(/\+/g, ' '))
						}
					}
				}
				// 如果没有从 headers 获取到文件名，可以自己指定一个
				if (!fileName) {
					fileName = '权限数据'
				}

				// 创建 Blob 对象
				const blob = new Blob([response.data], { type: contentType })

				// 创建下载链接
				const downloadUrl = window.URL.createObjectURL(blob)

				// 创建隐藏的可下载链接
				const a = document.createElement('a')
				a.style.display = 'none'
				a.href = downloadUrl
				a.download = fileName

				// 添加到 DOM 并立即点击它
				document.body.appendChild(a)
				a.click()

				// 清理：移除 DOM 元素并释放 Blob URL
				document.body.removeChild(a)
				window.URL.revokeObjectURL(downloadUrl)
				this.$message.success("导出成功")
			} catch (error) {
				console.error('文件下载失败:', error)
			}
			this.exportLoading = false
		},
		showFunctionPower(row) {
			this.dialog.show = true
			this.$nextTick(() => {
				this.$refs.showPower.open().setData(row, true)
			})
		},
		showDataPower(row) {
			this.dialog.show = true
			this.$nextTick(() => {
				this.$refs.showPower.open().setData(row, false)
			})
		}
	}
}
</script>

<style>
/* 针对 el-table 列中需要限制文本长度并以省略号表示的样式 */
.el-table .long-text div.cell {
	white-space: nowrap !important;
	overflow: hidden !important;
	text-overflow: ellipsis !important;
}
</style>
